package cn.juque.jdfsystem.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.juque.common.constants.YesOrNoEnum;
import cn.juque.jdfsystem.entity.FileInfo;
import cn.juque.jdfsystem.service.IFileInfoService;
import cn.juque.lucenecandy.core.base.QueryWrapperBuilder;
import cn.juque.lucenecandy.helper.IndexHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.BooleanClause;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>ClearInValidFileTask</li>
 * </ul>
 * @date 2023-01-18 10:41:47
 **/
@Slf4j
@Service("clearInValidFileTask")
public class ClearInValidFileTask extends AbstractTask {

    @Resource
    private IFileInfoService fileInfoService;

    @Resource
    private IndexHelper indexHelper;

    /**
     * 任务逻辑
     *
     * @param args 参数
     */
    @Override
    public void execute(String[] args) {
        if (!Boolean.TRUE.equals(super.registerInfoCache.checkMinHashCode())) {
            return;
        }
        // 默认清除7天前无效的文件
        Date date = DateUtil.offsetDay(new Date(), -7);
        Integer maxDate = Integer.parseInt(DateUtil.format(date, DatePattern.PURE_DATE_PATTERN));
        QueryWrapperBuilder<FileInfo> queryWrapperBuilder = new QueryWrapperBuilder<>(FileInfo.class);
        queryWrapperBuilder.matchRange(FileInfo::getCreateDate, Integer.MIN_VALUE, maxDate, BooleanClause.Occur.MUST);
        queryWrapperBuilder.matchInt(FileInfo::getValidFlag, YesOrNoEnum.NO.getCode(), BooleanClause.Occur.MUST);
        List<FileInfo> list = this.indexHelper.search(queryWrapperBuilder.build());
        if (CollUtil.isEmpty(list)) {
            return;
        }
        // 删除文件信息
        List<String> ids = list.stream().map(FileInfo::getId).collect(Collectors.toList());
        this.fileInfoService.deleteInfo(ids);
        log.info("预计清除无效文件总数:{}", ids.size());
    }

    /**
     * 设置随机休眠等待最大时长 单位：秒
     *
     * @return 秒
     */
    @Override
    protected Integer initSleepTimes() {
        return null;
    }

    @Override
    protected String getTaskName() {
        return "ClearInValidFileTask";
    }
}
